package com.weiyin.examination.http;


import android.nfc.Tag;

import com.weiyin.examination.http.apiservice.CoolService;
import com.weiyin.examination.util.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * @author njf
 */
public class DataService {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 10000000; // 超时时间
    private static final String CHARSET = "utf-8"; // 设置编码
    public static final String SUCCESS = "1";
    public static final String FAILURE = "0";

    private CoolService coolService;


    public DataService(CoolService coolService) {
        this.coolService = coolService;
    }

    public void getPaper(String regNumber, String paperId, String level, HttpRequestListener<ResponseBody> subscriber) {
        Map<String, String> params = new HashMap<>(2);
        params.put("regNumber", regNumber);
        params.put("paperId", paperId);
        params.put("level", level);
        Observable<ResponseBody> observable = coolService.getPaper(params);
        onSubscript(observable, subscriber, RequestUrl.PATH_APP);
    }

    public void down(String fileUrl, Callback<ResponseBody> callback) {
        Call<ResponseBody> call = coolService.downloadFileWithDynamicUrlSync(RetrofitClient.BASE_URL + fileUrl);
        LogUtil.i(TAG, RetrofitClient.BASE_URL + fileUrl);
        call.enqueue(callback);
    }

    /**
     * @param number 准考证号
     * @param name   姓名
     */
    public void login(String number, String name, HttpRequestListener<ResponseBody> subcriber) {
        Observable<ResponseBody> observable = coolService.login(number, name);
        onSubscript(observable, subcriber, RequestUrl.LOGIN);
    }

    public void fileUpload(File file, HttpRequestListener<ResponseBody> subcriber) {
        LogUtil.i("data",file.getName());
        RequestBody fileRQ = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part part =
                MultipartBody.Part.createFormData("file", file.getName(), fileRQ);
        Observable<ResponseBody> observable = coolService.fileUpload(part);
        onSubscript(observable, subcriber, RequestUrl.fileUpload);
    }

    public void updateScore(Map<String, String> map, HttpRequestListener<ResponseBody> subcriber) {
        Observable<ResponseBody> observable = coolService.uploadScore(map);
        onSubscript(observable, subcriber, RequestUrl.uploadScore);
    }

    public boolean writeResponseBodyToDisk(ResponseBody body, File futureStudioIconFile) {
        try {
            // todo change the file location/name according to your needs

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;

                    LogUtil.i(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
                }

                outputStream.flush();

                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }

    private void onSubscript(Observable<ResponseBody> observable, final HttpRequestListener<ResponseBody> listener, final String tag) {
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {
                        listener.onCompleted(tag);
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.onError(e, tag);
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        listener.onNext(responseBody, tag);
                    }
                });
    }
}
